﻿#include "tetrispiece.h"

void TetrisPiece::setRandomShape()
{
    setShape(PieceShape(QRandomGenerator::global()->bounded(7) + 1));
}

void TetrisPiece::setShape(TetrisPiece::PieceShape shape)
{
    // 8种形状的方块，每个方块有4小方块，每个小方块有x,y坐标
    static const int coordsTable[8][4][2] = {
        { {0, 0}, {0, 0}, {0, 0}, {0, 0} },
        { {0, -1}, {0, 0}, {-1, 0}, {-1, 1} },
        { {0, -1}, {0, 0}, {1, 0}, {1, 1} },
        { {0, -1}, {0, 0}, {0, 1}, {0, 2} },
        { {-1, 0}, {0, 0}, {1, 0}, {0, 1} },
        { {0, 0}, {1, 0}, {0, 1}, {1, 1} },
        { {-1, -1}, {0, -1}, {0, 0}, {0, 1} },
        { {1, -1}, {0, -1}, {0, 0}, {0, 1} }
    };

    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 2; ++j) {
            setX(i, coordsTable[shape][i][0]);  // 设置 x 坐标
            setY(i, coordsTable[shape][i][1]);  // 设置 y 坐标
        }
    }
    pieceShape = shape;
}

int TetrisPiece::minX() const
{
    int min = coords[0].x();
    for (int i = 1; i < 4; ++i)
        min = qMin(min, coords[i].x());
    return min;
}

int TetrisPiece::maxX() const
{
    int max = coords[0].x();
    for (int i = 1; i < 4; ++i)
        max = qMax(max, coords[i].x());
    return max;
}

int TetrisPiece::minY() const
{
    int min = coords[0].y();
    for (int i = 1; i < 4; ++i)
        min = qMin(min, coords[i].y());
    return min;
}

int TetrisPiece::maxY() const
{
    int max = coords[0].y();
    for (int i = 1; i < 4; ++i)
        max = qMax(max, coords[i].y());
    return max;
}

TetrisPiece TetrisPiece::rotatedLeft() const
{
    if (pieceShape == SquareShape)
        return *this;

    TetrisPiece result;
    result.pieceShape = pieceShape;
    for (int i = 0; i < 4; ++i) {
        result.setX(i, y(i));
        result.setY(i, -x(i));
    }
    return result;
}

TetrisPiece TetrisPiece::rotatedRight() const
{
    if (pieceShape == SquareShape)
        return *this;

    TetrisPiece result;
    result.pieceShape = pieceShape;
    for (int i = 0; i < 4; ++i) {
        result.setX(i, -y(i));
        result.setY(i, x(i));
    }
    return result;
}

QColor TetrisPiece::color() const
{
    static const QColor colors[] = {
        QColor(0, 0, 0),
        QColor(231, 76, 60),    // 红色 - Z
        QColor(46, 204, 113),   // 绿色 - S
        QColor(52, 152, 219),   // 蓝色 - I
        QColor(155, 89, 182),   // 紫色 - T
        QColor(241, 196, 15),   // 黄色 - O
        QColor(230, 126, 34),   // 橙色 - L
        QColor(41, 128, 185)    // 深蓝 - J
    };
    return colors[pieceShape];
}
